package utils

import (
	"github.com/shirou/gopsutil/process"
	"log"
	"procPacket/model"
	"strings"
)

// GetProcByName 通过进程名获取所有的进程
func GetProcByName(name string) (res []*process.Process) {
	processes, err := process.Processes()
	if err != nil {
		log.Println("GetProcIdByName Error -> ", err.Error())
		return
	}
	for _, proc := range processes {
		procName, err := proc.Name()
		if err != nil {
			log.Println("get procName error -> ", err.Error())
			continue
		}
		if procName == name {
			res = append(res, proc)
		}
	}
	return
}

func GetProcFrontByName(name string) (res []*model.Proc) {
	processes, err := process.Processes()
	if err != nil {
		log.Println("GetProcIdByName Error -> ", err.Error())
		return
	}
	for _, proc := range processes {
		procName, err := proc.Name()
		if err != nil && !strings.Contains(err.Error(), "couldn't find pid") {
			log.Println("get procName error -> ", err.Error())
			continue
		}
		if procName == name {
			var procFront = &model.Proc{}
			procFront.Pid = proc.Pid
			procFront.Name = name
			cmdline, err := proc.Cmdline()
			if err != nil {
				log.Println("get cmdline error -> ", err.Error())
			} else {
				procFront.Line = cmdline
			}
			res = append(res, procFront)
		}
	}
	return
}
